<template>
  <!-- 销售订单 列表 -->
  <div class="app-container jklis">
    <el-form :model="queryParams" ref="queryForm" :inline="true" class="search-form-new" label-width="90px">
      <el-form-item el-form-item label="店铺" prop="status" v-hasPermi="['searchTenantID']">
        <el-select v-model="queryParams.tenantId" placeholder="请选择店铺" clearable filterable>
          <el-option v-for="dict in tenantList" :key="dict.tenantId" :label="dict.tenantName" :value="dict.tenantId" />
        </el-select>
      </el-form-item>
      <el-form-item  label-width="70px" label="部门" prop="deptIdList" v-hasPermi="['goods:list:deptSearch']">
        <el-select  class="bumen" collapse-tags v-model="queryParams.deptIdList" placeholder="请选择" multiple clearable filterable>
          <el-option v-for="dict in allDepts" :key="dict.deptId" :label="dict.deptName" :value="dict.deptId" />
        </el-select>
      </el-form-item>
      <el-form-item label="订单类型" prop="orderType">
        <el-select v-model="queryParams.orderType" placeholder="请选择订单类型" clearable filterable>
          <el-option v-for="(item,key) in commonMaps.orderTypeMap" :key="key" :label="item.label" :value="key" />
        </el-select>
      </el-form-item>
      <el-form-item label="交易类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择交易类型" clearable filterable>
          <el-option v-for="(item,key) in commonMaps.orderJiaoyiTypeMap" :key="key" :label="item.label" :value="key" />
        </el-select>
      </el-form-item>
      <el-form-item label="支付状态" prop="salePay">
        <el-select v-model="queryParams.salePay" placeholder="请选择支付状态" clearable filterable>
          <el-option label="已支付" :value="2" />
          <el-option label="未支付" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="换绑状态" prop="changePhoneState">
        <el-select v-model="queryParams.changePhoneState" placeholder="请选择换绑状态" clearable filterable>
          <el-option label="已换绑" :value="2" />
          <el-option label="未换绑" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="销售渠道" prop="saleChannel">
        <el-select v-model="queryParams.saleChannel" placeholder="请选择渠道" clearable filterable>
          <el-option v-for="(item,key) in qudaoList" :key="key" :label="item.name" :value="item.name" />
        </el-select>
      </el-form-item>
      <el-form-item label="买家名称" prop="saleChannel">
        <el-input v-model="queryParams.saleChannel" placeholder="请输入买家名称" clearable />
      </el-form-item>
      <el-form-item label="销售人" prop="saleUserId">
        <el-select filterable clearable v-model="queryParams.saleUserId" placeholder="请选择销售人">
          <el-option v-for="(item ,key) in yuangongList" :key="key" :label="item.nickName" :value="item.userId" />
        </el-select>
      </el-form-item>
      <el-form-item label="供货商" prop="supplyChannel">
        <el-input v-model="queryParams.supplyChannel" placeholder="请输入供货商" clearable />
      </el-form-item>
      <el-form-item label="订单号" prop="no">
        <el-input v-model="queryParams.no" placeholder="请输入订单号" clearable />
      </el-form-item>
      <el-form-item label="三方订单号" prop="otherNo">
        <el-input v-model="queryParams.otherNo" placeholder="请输入三方订单号" clearable />
      </el-form-item>
      <el-form-item label="商品编号" prop="goodsId">
        <el-input v-model="queryParams.goodsId" placeholder="请输入商品编号" clearable />
      </el-form-item>
      <el-form-item label="游戏账号" prop="realAccountNumber">
        <el-input v-model="queryParams.realAccountNumber" placeholder="请输入游戏账号" clearable />
      </el-form-item>
      <el-form-item label="游戏名称" prop="gameId">
        <el-select v-model="queryParams.gameId" placeholder="请选择游戏" clearable>
          <el-option v-for="dict in allGameList" :key="dict.id" :label="dict.name" :value="dict.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="queryParams.remark" placeholder="请输入备注" clearable />
      </el-form-item>

      <el-form-item label="创建时间" prop="">
        <el-date-picker style="width: 300px;" clearable v-model="timer1" value-format="yyyy-MM-dd" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <!-- <el-form-item label="支付时间" prop="">
        <el-date-picker clearable v-model="timer2" value-format="yyyy-MM-dd" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item> -->
      <el-form-item label="完成时间" prop="">
        <el-date-picker style="width: 300px;" clearable v-model="timer3" value-format="yyyy-MM-dd" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item class="btns">
        <el-button type="primary" icon="el-icon-search" @click="search">搜索</el-button>
        <el-button icon="el-icon-refresh" type="warning" @click="resetQuery">重置</el-button>
        <el-button v-if="checkPermi(['orderForTenant:addOrder'])" icon="el-icon-plus" type="success" @click="openCreateOrder">创建订单</el-button>
        <el-button style="margin-left: 10px" type="warning" icon="el-icon-setting" plain @click="headerSet">表头设置</el-button>
      </el-form-item>
    </el-form>
    <div class="zdy-main customTab customTabNew" v-loading="loading">
      <div class="tabs flex alc">
        <el-radio-group v-model="actived" @change="tabChange">
          <el-radio-button :label="tab.value" v-for="tab in commonMaps.orderStatusArr" :key="tab.value">{{ tab.name }}</el-radio-button>
        </el-radio-group>
        <div class="tongji_box" v-if="totalNumber">
          <span>
            总实付金额:
            <span class="price">{{ formatter(totalNumber.buyerActualAmountSum||0) }}</span>元
          </span>
          <span v-if="totalNumber.profileSum">
            总利润:
            <span class="price">{{ formatter(totalNumber.profileSum||0) }}</span>元
          </span>
        </div>
      </div>
      <div class="table_box table_box_new" v-if="columnList&&columnList.length">
        <el-table ref="tableRef" :data="tableData.records" border  stripe>
          <template v-for="column in columnList">
            <el-table-column :key="column.key" v-if="column.isShow" :label="column.label" :width="column.width" :min-width="column.minWidth" :prop="column.key" :sortable="column.sortable">
              <template slot-scope="scope">
                <template v-if="column.key=='sourceScen'">
                  <div>
                    {{scope.row.sourceScen?commonMaps.orderSource[scope.row.sourceScen].label:'无'}}
                  </div>
                </template>
                <template v-else-if="column.key=='orderType'">
                  <div>
                    <el-tag :type="commonMaps.orderTypeMap[scope.row.orderType].type">{{scope.row.orderType?commonMaps.orderTypeMap[scope.row.orderType].label:'无'}}</el-tag>
                  </div>
                </template>
                <template v-else-if="column.key=='type'">
                  <div>
                    <el-tag :type="commonMaps.orderJiaoyiTypeMap[scope.row.type].type">{{scope.row.type?commonMaps.orderJiaoyiTypeMap[scope.row.type].label:'无'}}</el-tag>
                  </div>
                </template>
                <template v-else-if="column.key=='orderStatus'">
                  <div>
                    <el-tag :type="commonMaps.orderStatusMapType[scope.row.orderStatus].type">{{scope.row.orderStatus?commonMaps.orderStatusMapType[scope.row.orderStatus].label:'无'}}</el-tag>
                  </div>
                </template>
                <template v-else-if="column.key=='no'">
                  <div>
                    <span @click="goOrderDetail(scope.row)" class="link">
                      {{ scope.row.no }}
                    </span>
                  </div>
                </template>
                <template v-else-if="column.key=='realAccountNumber'">
                  <span>{{scope.row.realAccountNumber||'暂无'}}</span>
                </template>
                <template v-else-if="column.key=='saleChannel'">
                  <template v-if="(scope.row.sourceScen==4||scope.row.sourceScen==5)&&scope.row.type!=2">
                    {{ scope.row.saleChannel }}
                  </template>
                  <template v-else>
                    <!-- 1 b2c 3 c2c  C端 -->
                    <span v-if="scope.row.type==1||scope.row.type==3" class="link" @click="conactbuyer(scope.row.saleChanelId)">{{ scope.row.saleChannel }}</span>
                    <!-- b2b -->
                    <span v-if="scope.row.type==2" class="link" @click="openIM(scope.row,'buyer')">{{ scope.row.saleTenantName }}</span>
                  </template>

                </template>
                <template v-else-if="column.key=='guaranteeAmount'">
                  <div v-if="scope.row.guaranteeAmount">
                    <span v-if="scope.row.guaranteeType">{{ scope.row.guaranteeType }}：</span>
                    <span>{{ scope.row.guaranteeAmount }}</span>
                  </div>
                </template>
                <template v-else-if="column.key=='salePay'">
                  <span style="color: red;" v-if="scope.row.payStatus==5">(已退款)</span>
                  <span style="margin-left: 5px;" v-if="scope.row.salePay==2&&(scope.row.isHuifu==2||scope.row.paySelf==2)&&scope.row.orderStatus==2&&scope.row.payStatus!=5">
                    <!-- 汇付支付的  交易失败的 但是没显示已退款的，有问题 -->
                    <span class="link" @click="checkTuikuan(scope.row)">更新</span>
                    <br />
                  </span>

                  <span>

                    <el-tag type="success" v-if="scope.row.salePay==2">已支付</el-tag>
                    <el-tag type="danger" v-else>未支付</el-tag>
                  </span>
                </template>
                <template v-else-if="column.key=='changePhoneState'">
                  <span>
                    <el-tag type="success" v-if="scope.row.changePhoneState&&scope.row.changePhoneState==2">已换绑</el-tag>
                    <el-tag type="danger" v-else>未换绑</el-tag>
                    <span style="color: red;" v-if="scope.row.changePhoneState==1">
                      {{ getDay(scope.row.createTime) }}
                    </span>
                  </span>
                </template>
                <template v-else-if="column.key=='afterSaleState'">

                  <span v-if="scope.row.afterSaleState">售后{{scope.row.afterSaleState?commonMaps.afterOrderStateMap[scope.row.afterSaleState]:''}} <br /></span>
                </template>

                <template v-else-if="column.key=='supplyChannel'">
                  <template v-if="scope.row.sourceScen==5">
                    {{ scope.row.supplyChannel }}
                  </template>
                  <template v-else>
                    <span class="link" @click="lianxiGonghuo(scope.row)">
                      <span v-if="scope.row.orderType==1">
                        {{ scope.row.supplyChannel }}
                      </span>
                      <span v-else>
                        <span v-if="allYouzhiMap&&allYouzhiMap[scope.row.supplyChanelId]">
                          <youzhiName :name="scope.row.supplyChannel"></youzhiName>
                        </span>
                        <span v-else>
                          {{ scope.row.supplyChannel }}
                        </span>
                      </span>
                    </span>
                  </template>
                </template>
                <template v-else-if="column.key=='changePhoneImg'||column.key=='orderImg'">
                  <img-box width="50px" height="50" :img="scope.row[column.key]"></img-box>
                </template>
                <template v-else-if="column.key=='img'">
                  <img-box width="50px" height="50" isWrap="nowrap" :img="scope.row[column.key]"></img-box>
                </template>
                <template v-else-if="column.key=='remark'">
                  <el-tooltip class="item" effect="dark" :content="scope.row[column.key]" placement="top-start">
                    <div class="zdy-des">{{ scope.row[column.key] }}</div>
                  </el-tooltip>
                </template>

                <template v-else-if="column.key=='sendState'">
                  <span>{{scope.row.sendState?commonMaps.sendStateMap[scope.row.sendState]:''}}</span>
                </template>
                <template v-else-if="column.key=='actualAmount'">
                  <b style="color: red;font-size: 15px;">{{scope.row.actualAmount}}</b>
                </template>
                <template v-else-if="column.key=='profits'">
                  <b style="color: #07c160;font-size: 15px;">{{scope.row.profits}}</b>
                </template>
                <template v-else-if="column.key=='otherFee'">
                  <div class="link" v-if="scope.row.otherFee" @click="openOtherFeeDialog(scope.row)">
                    {{ getOtherFeeTotal(scope.row.otherFee) }}
                  </div>
                  <span v-else>
                    <el-button type="text" @click="openOtherFeeDialog(scope.row)">0</el-button>
                  </span>
                </template>
                <template v-else>
                  <span>{{scope.row[column.key]||''}}</span>
                </template>
              </template>
            </el-table-column>
          </template>
          <el-table-column fixed="right" label="操作" min-width="260">
            <template slot-scope="scope">
              <template v-if="scope.row.sourceScen!=5">
                <el-button type="edit" @click="editPrice(scope.row)" v-if="(scope.row.sourceScen!=4||(scope.row.type==2))&&((scope.row.orderStatus == 3||scope.row.orderStatus == 4)&&scope.row.salePay==1)&&checkPermi(['orderForTenant:editPrice'])">改价</el-button>
                <el-button type="edit" @click="editRemark(scope.row)" v-if="(scope.row.sourceScen!=4||scope.row.type==2)&&checkPermi(['orderForTenant:editRemark'])">修改信息</el-button>
                <el-button type="text" @click="transJiaoYiZhong(scope.row.id)" v-if="(scope.row.type==1||scope.row.type==2)&&scope.row.orderStatus == 3">挂账</el-button>
                <!-- 群组相关操作 -->
                <template v-if="scope.row.sourceScen!=4">
                  <el-button type="text" v-if="!scope.row.msgGroupInfoId&&!scope.row.toGroup&&scope.row.orderStatus != 3" @click="onKeyGroup(scope.row)">一键拉群</el-button>
                  <el-button type="text" v-if="scope.row.toGroup" @click="groupChat(scope.row)">进入群组</el-button>
                  <el-button type="text" v-if="scope.row.msgGroupInfoId&&scope.row.toGroup" @click="cancelGroup(scope.row.id)">解散群组</el-button>
                  <el-button type="text" v-if="
                      scope.row.msgGroupInfoId &&
                      !scope.row.toGroup
                    " @click="recoverGroup(scope.row.id)">恢复群组</el-button>
                </template>
                <el-button type="text" v-if="scope.row.type == 2&&scope.row.orderStatus == 4&&scope.row.sendState==1" @click="sendGoods(scope.row)">发货</el-button>
                <el-button v-if="(scope.row.type == 1||scope.row.type == 3)&&scope.row.orderStatus == 4&&checkPermi(['orderForTenant:finishOrder'])" type="add" @click="completion(scope.row)">完成交易</el-button>
                <el-button type="del" v-if="((scope.row.orderStatus != 2&&scope.row.salePay==1)||(scope.row.type==2&&scope.row.orderStatus != 2&&scope.row.orderStatus != 4&&scope.row.orderStatus!=1))&&checkPermi(['orderForTenant:cancelOrder'])"
                           @click="cancelOrder(scope.row,'cancel')">取消交易</el-button>
                <el-button type="del" v-if="((scope.row.isHuifu == 2||scope.row.paySelf == 2)&&scope.row.payStatus==2&&scope.row.orderStatus == 4)&&checkPermi(['orderForTenant:cancelOrder'])" @click="cancelOrder(scope.row,'cancelAndRefund')">取消并退款</el-button>
              </template>
              <el-button type="edit" @click="editPayStatus(scope.row)"
                         v-if="scope.row.sourceScen!=4&&scope.row.sourceScen!=5&& (!scope.row.payStatus||scope.row.payStatus==1)&&scope.row.type==1&&scope.row.orderStatus != 101&&scope.row.orderStatus != 2&&scope.row.orderStatus != 3&&checkPermi(['orderForTenant:editPayState'])">更改支付状态</el-button>
              <el-button type="text" @click="afterSale(scope.row)"
                         v-if="((scope.row.orderStatus==4&&scope.row.isHuifu!=2&&scope.row.paySelf!=2&&scope.row.salePay==2&&scope.row.afterSaleState!=3)||(scope.row.orderStatus==1&&scope.row.afterSaleState!=3&&scope.row.salePay==2))&&checkPermi(['orderForTenant:addAfterOrder'])">申请售后</el-button>

              <el-button type="text" @click="afterSaleView(scope.row.id)" v-if="scope.row.type==1&&actived=='101'&&checkPermi(['orderForTenant:viewAfterOrder'])">查看售后</el-button>
              <template v-if="(scope.row.sourceScen==5||scope.row.sourceScen==4)&&scope.row.type!=2">
                <el-button type="edit" v-if="scope.row.isAudit!=2&&checkPermi(['orderForTenant:editOrder'])" @click="openEditOrder(scope.row.id)">编辑订单</el-button>
                <el-button type="del" v-if="scope.row.sourceScen==5&&scope.row.isAudit!=2&&checkPermi(['orderForTenant:delOrder'])" @click="delSelfOrder(scope.row.id)">删除订单</el-button>
              </template>
              <!-- <el-button type="text" @click="laqun(scope.row.id)" >拉群</el-button> -->
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="tableData.total > 0" :total="tableData.total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
      </div>
      <!-- </el-tab-pane>
      </el-tabs> -->
    </div>

    <h5Dialog ref="h5Dialog"></h5Dialog>
    <cancelOrderSure ref="cancelOrderSure"></cancelOrderSure>
    <orderDetailDialog ref="orderDetailDialog"></orderDetailDialog>
    <completionOrder ref="completionOrder"></completionOrder>
    <editPrice ref="editPrice"></editPrice>
    <payEdit ref="payEdit"></payEdit>
    <!-- <msgHistory ref="msgHistory" :showDialog="showMsgHis" @close="guanbi" :sessionId="toGroups"></msgHistory> -->
    <sendGoodsDialog ref="sendGoodsDialog"></sendGoodsDialog>
    <afterSellAdd ref="afterSellAdd"></afterSellAdd>
    <afterSellViewBuyer ref="afterSellViewBuyer"></afterSellViewBuyer>
    <editRemarkDialog ref="editRemarkDialog"></editRemarkDialog>
    <kefuList ref="kefuList"></kefuList>
    <createSaleOrderCustom @addSuccess="getList" ref="createSaleOrderCustom"></createSaleOrderCustom>

    <editTableHeader ref="editTableHeader" @save="headerSave"></editTableHeader>
    <!-- 其他成本弹窗 -->
    <otherFeeDialog ref="otherFeeDialog"></otherFeeDialog>
  </div>
</template>

<script>
import h5Dialog from "@/components/h5Dialog.vue";
import editRemarkDialog from "./components/editRemarkDialog.vue";
import sendGoodsDialog from "./components/sendGoods.vue";
import cancelOrderSure from "./components/cancelOrderSure.vue";
import completionOrder from "./components/completionOrder.vue";
import payEdit from "./components/payEdit.vue";
import editPrice from "./components/editPrice.vue";
// import msgHistory from "../../qunxinxi/msgHistory/index.vue";
import afterSellAdd from "./components/afterSellAdd.vue";
import afterSellViewBuyer from "../saleAfterOrder/components/afterSellView.vue";
// import orderDetail from "./components/orderDetail.vue";
import orderDetailDialog from "./components/orderDetailDialog";
import orderApi from "@/api/pickUp/order.js";
import { getDicts } from "@/api/system/dict/data";
import { getUser } from "@/api/system/user";
// import Cookies from "js-cookie";
// import openWindownFn from "@/utils/openUrlByWindow.js";
import kefuList from "@/components/common/kefuList.vue";

import createSaleOrderCustom from "./components/createSaleOrderCustom.vue";

import { saleOrderHeaderList } from "../../../utils/tableHeaders";

import supplyConfigApi from "@/api/system/supplyConfig";

import editTableHeader from "../../../components/common/editTableHeader.vue";
import { getUserListHeaderByType } from "../../../api/tableHeader";
import { listDept } from "@/api/system/dept";

import otherFeeDialog from "./components/otherFeeDialog.vue";

import otherChannels from "@/api/retrieveManage/otherChannels"
export default {
  name: "SaleOrderPage",
  components: {
    h5Dialog,
    cancelOrderSure,
    orderDetailDialog,
    editPrice,
    completionOrder,
    payEdit,
    afterSellAdd,
    afterSellViewBuyer,
    editRemarkDialog,
    kefuList,
    sendGoodsDialog,

    createSaleOrderCustom,
    editTableHeader,
    otherFeeDialog
  },
  data() {
    return {
      timer1: [],
      timer2: [],
      timer3: [],
      showMsgHis: false, //显示历史消息
      toGroups: "", //历史消息群id
      // 提号时间，商品ID 游戏类型 区服 实名状态   游戏账号【对应的商品链接】
      tableData: {
        records: [],
        total: 0,
      },
      btnLoading: false,
      loading: false,
      actived: 3,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderStatus: 3,
        account: null,
        accountId: null,
        tel: null,
        dataType: "all",
        gameId:'',
        deptIdList:''
      },
      copyVlaue: "",
      IMhost: "",
      columnList: [],
      yuangongList: [],
      totalNumber: null,
      allDepts: [],
      qudaoList:[]
    };
  },
  computed: {
    tenantList() {
      return this.$store.getters.tenantList;
    },
    allYouzhiMap() {
      return this.$store.getters.allYouzhiMap;
    },
    formatter() {
      return (val) => {
        let formatter = new Intl.NumberFormat("en-US");
        const formattedNumber = formatter.format(val);
        return formattedNumber;
      };
    },
    allGameList() {
      return this.$store.getters.allGameList;
    },
    // 计算未换绑时间
    getDay() {
      return (val) => {
        let result = "";
        const now = new Date();
        const start = new Date(val);
        if (start) {
          // 计算时间差（毫秒）
          const timeDiff = now.getTime() - start.getTime();
          if (timeDiff > 0) {
            // 将毫秒转换为天数（1天 = 24 * 60 * 60 * 1000毫秒）
            const daysDiff = Math.floor(timeDiff / (1000 * 60 * 60 * 24));
            if (daysDiff > 0) {
              result = `${daysDiff}天`;
            }
          }
        }
        return result;
      };
    },
    // 计算其他成本
    getOtherFeeTotal(){
      return (str)=>{
        let total = 0
        const arr = JSON.parse(str)
        if(arr&&arr.length){
          arr.forEach(r=>{
            if(r.price){
              total = total + Number(r.price)
            }
          })
        }
        return Math.round(total*100)/100
      }
    }
  },
  created() {
    if (this.$route.query.orderStatus) {
      this.actived = this.$route.query.orderStatus;

      this.queryParams = { ...this.queryParams, ...this.$route.query };
      if(this.$route.query.deptIdList){
        this.queryParams.deptIdList = JSON.parse(this.queryParams.deptIdList)
      }
      if(this.queryParams.finishTimeStart&&this.queryParams.finishTimeEnd){
        this.timer3 = [this.queryParams.finishTimeStart,this.queryParams.finishTimeEnd]
      }
      if(this.queryParams.gameId){
        this.queryParams.gameId= Number(this.queryParams.gameId)
      }
      if(this.queryParams.saleUserId){
        this.queryParams.saleUserId= Number(this.queryParams.saleUserId)
      }
    }
    this.getList();
    this.getTableHeader();
    this.getIMhost();
    this.getYuangongList();
    this.getDeptList()
    this.getQudaoList()
  },
  activated() {
    // if (this.$router.currentRoute.query.orderStatus) {
    //   this.actived = this.$router.currentRoute.query.orderStatus;
    //   this.queryParams.orderStatus =
    //     this.$router.currentRoute.query.orderStatus;
    // }
    // this.getList();
  },
  methods: {
    // 打开表头设置
    headerSet() {
      this.$refs.editTableHeader.open(2);
    },
    // 查询表头
    getTableHeader() {
      getUserListHeaderByType({ type: 2 }).then((res) => {
        if (res.data && res.data.settingsJson) {
          this.columnList = JSON.parse(res.data.settingsJson);
        } else {
          this.columnList = [...saleOrderHeaderList];
        }
      });
    },
    // 查询自定义平台渠道
    getQudaoList() {
        otherChannels.getQudaoList({
            isPage: 2,
            type: 2,
            pageNum: 1,
            pageSize: 100
        }).then((response) => {
            this.qudaoList = response.rows;
        });
    },
    // 查询部门列表
    async getDeptList() {
      try {
        if (this.checkPermi(["goods:list:deptSearch"])) {
          const { data } = await listDept();
          // console.log("%c Line:775 🌽 data", "color:#93c0a4", data);
          this.allDepts = data.filter((r) => r.parentId != 100);
        }
      } catch (error) {}
    },
    // headerSave
    headerSave(listJson) {
      this.columnList = [];
      this.$nextTick(() => {
        this.columnList = JSON.parse(listJson);
        this.$nextTick(() => {
          this.$refs.tableRef.doLayout();
        });
      });
      // this.getTableHeader();
    },

    // 获取所有员工列表
    getYuangongList() {
      supplyConfigApi
        .getAllUserList({
          userNewType: 1,
        })
        .then((res) => {
          this.yuangongList = res.rows;
        });
    },
    // 打开自建订单弹窗
    openCreateOrder() {
      this.$refs.createSaleOrderCustom.open();
    },
    // 拉群 测试用
    laqun(id) {
      orderApi.pullGroupB2B({
        id: id,
      });
    },
    // 获取IM域名
    getIMhost() {
      getDicts("IMhost").then((res) => {
        if (res.data && res.data.length) {
          this.IMhost = res.data[0].dictValue;
        }
      });
    },
    // 联系 店铺
    openIM(row, flag) {
      // 打开客服列表
      if (flag == "buyer") {
        // // b2b 联系买家
        this.$refs.kefuList.open(row.saleTenantId, 1, {
          gameId: row.gameId,
          gameName: row.gameName,
        });
      } else {
        // 联系供货商
        this.$refs.kefuList.open(row.supplyTenantId, 1, {
          gameId: row.gameId,
          gameName: row.gameName,
        });
      }
    },
    // 联系供货商
    lianxiGonghuo(row){
      if(row.type==3){
        // c2c. 直接联系用户
        this.getOtherUserInfo(row.supplyChanelId);
      }else{
        this.openIM(row,'supply')
      }
    },
    // 跳转客服系统
    goIM(IMid, chatType) {
      // let token = Cookies.get("Admin-Token");
      let obj = {
        type: "goChat",
        hxusername: IMid,
        chatType: chatType,
      };
      // 告诉IM系统，需要跳转聊天页
      this.$store.dispatch("postMsgToIM", obj);
    },
    // 查询用户信息
    async getOtherUserInfo(userId) {
      let { data } = await getUser(userId);
      //console.log("%c Line:200 🍞 data", "color:#2eafb0", data);
      this.goIM(data.hxusername, "singleChat");
    },
    // 联系买家/卖家
    async conactbuyer(userId) {
      await this.getOtherUserInfo(userId);
    },
    // 进入群组会话
    groupChat(row) {
      //       if (window.frames.length > 0) {
      //   //console.log("当前窗口有子窗口");
      // } else {
      //   //console.log("当前窗口没有子窗口");
      // }

      // 获取群组hxid
      orderApi
        .getToGroup({
          id: row.id,
        })
        .then((res) => {
          //console.log("%c Line:404 🥒 res", "color:#93c0a4", res);
          if (res.code == 200 && res.data.del == 1) {
            this.goIM(res.data.toGroup, "groupChat");
          } else {
            this.$message.error("未创建群组，请先创建群组!");
          }
        });
    },
    // 一键建群
    onKeyGroup(row) {
      /**卖家：${
        row.supplyChannel
      }<br/> */
      let str = `买家：${row.saleChannel}<br/>订单状态：${
        this.commonMaps.orderStatusMap[row.orderStatus]
      }<br/>商品编号：${row.goodsId}<br/>商品类型：${
        row.gameName
      }<br/>支付金额：${row.actualAmount}`;
      this.$confirm(str, "一键拉群", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        dangerouslyUseHTMLString: true,
      })
        .then(() => {
          let obj = {
            id: row.id,
          };
          orderApi.pullGroup(obj).then((res) => {
            this.$message(res.msg);
            if (res.code == 200) {
              this.getList();
              // 跳转到群聊
              this.goIM(res.data.toGroup, "groupChat");
            }
          });
        })
        .catch(() => {});
    },
    // 解散群组
    cancelGroup(id) {
      this.$confirm("确定解散该群组吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let obj = {
            id: id,
          };
          orderApi.cancelGroup(obj).then((res) => {
            this.$message(res.msg);
            if (res.code == 200) {
              this.getList();
            }
          });
        })
        .catch(() => {});
    },
    // 恢复群组
    recoverGroup(id) {
      this.$confirm("确定恢复该群组吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let obj = {
            id: id,
          };
          orderApi.recoveryGroup(obj).then((res) => {
            this.$message.success(res.msg);
            if (res.code == 200) {
              this.getList();
              this.goIM(res.data.toGroup, "groupChat");
            }
          });
        })
        .catch(() => {});
    },
    // 打开历史消息
    openMsgHis(row) {
      // 获取群组hxid
      orderApi
        .getToGroup({
          id: row.id,
        })
        .then((res) => {
          //console.log("%c Line:404 🥒 res", "color:#93c0a4", res);
          if (res.code == 200) {
            this.toGroups = res.data.toGroup;
            this.showMsgHis = true;
          } else {
            this.$message.error("未找到群组");
          }
        });
    },
    // 关闭历史消息
    guanbi() {
      this.showMsgHis = false;
    },

    // 获取列表
    getList() {
      // queryParams 请求列表
      // 创建时间
      if (this.timer1 && this.timer1.length) {
        this.queryParams.createTimeStart = this.timer1[0];
        this.queryParams.createTimeEnd = this.timer1[1] + " " + "23:59:59";
      } else {
        this.queryParams.createTimeStart = "";
        this.queryParams.createTimeEnd = "";
      }
      //支付时间
      if (this.timer2 && this.timer2.length) {
        this.queryParams.payTimeStart = this.timer2[0];
        this.queryParams.payTimeEnd = this.timer2[1] + " " + "23:59:59";
      } else {
        this.queryParams.payTimeStart = "";
        this.queryParams.payTimeEnd = "";
      }
      //完成时间
      if (this.timer3 && this.timer3.length) {
        this.queryParams.finishTimeStart = this.timer3[0];
        this.queryParams.finishTimeEnd =this.timer3[1].length>10?this.timer3[1]: (this.timer3[1] + " " + "23:59:59");
      } else {
        this.queryParams.finishTimeStart = "";
        this.queryParams.finishTimeEnd = "";
      }

      this.loading = true;
      this.totalNumber = null;
      orderApi.getListNew(this.queryParams).then((res) => {
        this.loading = false;
        this.tableData.records = res.rows;
        this.tableData.total = res.total;
        if (res.params) {
          this.totalNumber = res.params;
        }
        // this.$nextTick(()=>{
        //   this.$refs.tableRef.doLayout();
        // })
      });
    },
    // tabs切换时触发
    tabChange() {
      this.queryParams.pageNum = 1;
      this.queryParams.orderStatus = this.actived;
      if (this.actived == "101") {
        // 售后
        this.queryParams.orderStatus = "";
        this.queryParams.afterSaleState = 100;
      } else {
        this.queryParams.afterSaleState = "";
      }
      this.getList();
    },
    // 复制成功和失败的方法
    onCopy(e) {
      this.$modal.msgSuccess("复制成功");
      this.copyVlaue = "";
    },
    onError() {
      this.$modal.msgError("复制失败");
      this.copyVlaue = "";
    },
    // 查询订单的退款状态
    checkTuikuan(row) {
      this.loading = true;
      orderApi
        .queryRefundInfo({
          id: row.id,
        })
        .then((res) => {
          this.loading = false;
          row.payStatus = res.data.payStatus;
          this.getList();
        })
        .catch((err) => {
          this.loading = false;
        });
    },
    //查看订单详情
    goOrderDetail(row) {
      this.$refs.orderDetailDialog.open(row.id, "kefu");
    },
    // 复制订单信息
    copyOrder(row) {
      // let link = this.PChost +'/pages/order/orderDetail?orderId='+row.id
      let str = `订单编号：${row.no}\n商品编号：${row.goodsId}\n游戏：${
        row.gameName
      }\n区服：${row.qufu}\n简介：${row.des.slice(0, 120)}\n图片：${
        row.titleImg
      }\n官方客服：${row.saleUserNickname}`;
      this.$copyText(str).then(() => {
        this.$message.success("已复制到剪切板");
      });
    },
    // // 打开发货弹窗
    sendGoods(row) {
      // this.showSendDialog = true
      this.$refs.sendGoodsDialog.open(row);
    },
    // // 编辑发货信息
    // editSendGoods(row, flag) {
    //   this.$refs.sendGoodsDialog.open(row, flag);
    // },
    // 转到交易中
    transJiaoYiZhong(id) {
      this.$confirm("确认将该订单转为交易中吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          orderApi.changeOrderStatus({ id: id }).then((res) => {
            this.$message({
              type: "success",
              message: "操作成功!",
            });
            this.getList();
          });
        })
        .catch(() => {});
    },
    // 更改支付状态
    editPayStatus(row) {
      this.$refs.payEdit.open(row, "kefu");
    },
    // 取消订单
    cancelOrder(row, flag) {
      this.$refs.cancelOrderSure.open(row, "kefu", flag);
    },
    // 编辑价格
    editPrice(row) {
      this.$refs.editPrice.open(row);
    },
    // 编辑其他成本
    openOtherFeeDialog(row){
      this.$refs.otherFeeDialog.open(row);
    },
    // 编辑备注
    editRemark(row) {
      this.$refs.editRemarkDialog.open(row);
    },
    // 完成订单
    completion(row) {

      this.$refs.completionOrder.open(row);
    },

    // 申请售后
    afterSale(row) {
      this.$refs.afterSellAdd.open(row);
    },
    // 查看售后
    afterSaleView(id) {
      this.$refs.afterSellViewBuyer.open(id);
    },
    // 编辑 自建订单
    openEditOrder(id) {
      this.$refs.createSaleOrderCustom.open("edit", id);
    },
    // 删除自建订单
    delSelfOrder(id) {
      this.$confirm(
        "删除后将无法查看且无法恢复，确定要删除该订单吗？",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          orderApi.delOrderBySelf({ id }).then((res) => {
            this.$message.success(res.msg);
            this.getList();
          });
        })
        .catch(() => {});
    },
    search() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.timer1 = [];
      this.timer2 = [];
      this.timer3 = [];
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        orderStatus: this.queryParams.orderStatus,
        dataType: "all",
        account: null,
        accountId: null,
        tel: null,
      };
      this.getList();
    },
    // 查看换绑信息
    changeInfo(row) {
      this.$refs.detailDialog.open(row.id);
    },
    // 每页条数改变
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.getList();
    },
    // 页码改变
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.getList();
    },
    exportOrder() {},
  },
};
</script>
<style lang="scss" scoped>
.link {
  color: blue;
  cursor: pointer;
}

</style>
